<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

//股东分红 团队分红
namespace app\common;
use think\facade\Db;
use think\facade\Log;
class Fenhong
{
	public static function jiesuan($aid,$starttime=0,$endtime=0){
		if($endtime == 0) $endtime = time();
		$sysset = Db::name('admin_set')->where('aid',$aid)->find();
		
		$where = [];
		$where[] = ['og.aid','=',$aid];
		$where[] = ['og.isfenhong','=',0];
		if($sysset['fhjiesuanbusiness'] == 1){ //多商户的商品是否参与分红
			
		}else{
			$where[] = ['og.bid','=','0'];
		}
		if($sysset['fhjiesuantime_type'] == 1) { //分红结算时间类型 0收货后，1付款后
			$where[] = ['og.status','in',[1,2,3]];
			$where[] = ['og.createtime','>=',$starttime];
			$where[] = ['og.createtime','<',$endtime];
			$where2 = $where;
		}else{
			$where[] = ['og.status','=','3'];
			$where2 = $where;
			$where[] = ['og.endtime','>=',$starttime];
			$where[] = ['og.endtime','<',$endtime];
			$where2[] = ['og.collect_time','>=',$starttime];
			$where2[] = ['og.collect_time','<',$endtime];
		}

		$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,o.paytime')->join('shop_order o','o.id=og.orderid')->where($where)->select()->toArray();
		if($oglist){
			if(false){}else{
				$update = ['og.isfenhong'=>1,'og.isteamfenhong'=>1];
			}
			Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,o.paytime')->join('shop_order o','o.id=og.orderid')->where($where)->update($update);
		}
		self::gdfenhong($aid,$sysset,$oglist,$starttime,$endtime);
		self::teamfenhong($aid,$sysset,$oglist,$starttime,$endtime);
		self::areafenhong($aid,$sysset,$oglist,$starttime,$endtime);
		self::product_teamfenhong($aid,$sysset,$oglist,$starttime,$endtime);
		self::level_teamfenhong($aid,$sysset,$oglist,$starttime,$endtime);
	}
	//股东分红
	public static function gdfenhong($aid,$sysset,$oglist,$starttime=0,$endtime=0,$isyj=0,$yjmid=0){
		if($endtime == 0) $endtime = time();
		if($isyj == 1 && !$oglist){
			//多商户的商品是否参与分红
			if($sysset['fhjiesuanbusiness'] == 1){
				$bwhere = '1=1';
			}else{
				$bwhere = [['og.bid','=','0']];
			}
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',$aid)->where('og.isfenhong',0)->where('og.status','in',[1,2,3])->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->order('og.id desc')->select()->toArray();
			}
		if(!$oglist) return ['commissionyj'=>0,'oglist'=>[]];
		//参与股东分红的等级
		$fhlevellist = Db::name('member_level')->where('aid',$aid)->where('fenhong','>','0')->order('sort desc,id desc')->column('*','id');
		if(!$fhlevellist) return ['commissionyj'=>0,'oglist'=>[]];
		
		$defaultCid = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 1)->value('id');
		if($defaultCid) {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->where('cid', $defaultCid)->column('id');
		} else {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->column('id');
		}

		$ogids = [];
		$midfhArr = [];
		$newoglist = [];
		$commissionyj = 0;
        $allfenhongprice = 0;
		foreach($oglist as $og){
			if(false){}else{
				$commissionpercent = 1;
				$moneypercent = 0;
			}
			if($sysset['fhjiesuantype'] == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'] * $og['num'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$member = Db::name('member')->where('id', $og['mid'])->find();
			$member_extend = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('mid', $og['mid'])->find();

			if(false){}else{
				$commissionpercent = 1;
				$moneypercent = 0;
			}
			if($sysset['fhjiesuantype'] == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'] * $og['num'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$allfenhongprice = $allfenhongprice + $fenhongprice;
			$member = Db::name('member')->where('id', $og['mid'])->find();
			$member_extend = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('mid', $og['mid'])->find();

			if($fhlevellist){
				$lastmidlist = [];
				foreach($fhlevellist as $fhlevel){
					$where = [];
					$where[] = ['aid', '=', $aid];
					$where[] = ['levelid', '=', $fhlevel['id']];
					$where[] = ['levelstarttime', '<', $og['createtime']]; //判断升级时间
					$where2 = [];
					$where2[] = ['ml.aid', '=', $aid];
					$where2[] = ['ml.levelid', '=', $fhlevel['id']];
					$where2[] = ['ml.levelstarttime', '<', $og['createtime']];
					if($fhlevel['fenhong_max_money'] > 0) {
						$where[] = ['total_fenhong_partner', '<', $fhlevel['fenhong_max_money']];
						$where2[] = ['m.total_fenhong_partner', '<', $fhlevel['fenhong_max_money']];
					}

					if($defaultCid > 0 && $defaultCid != $fhlevel['cid']) {
						//其他分组
						} else {
						//默认分组
						if ($fhlevel['fenhong_num'] > 0) {
							$midlist = Db::name('member')->where($where)->order('levelstarttime,id')->limit(intval($fhlevel['fenhong_num']))->column('id,total_fenhong_partner,levelstarttime', 'id');
						}else{
							$midlist = Db::name('member')->where($where)->column('id,total_fenhong_partner,levelstarttime','id');
						}
					}
					try {
						$levelup_order_mids = Db::name('member_levelup_order')->where('aid',$aid)->where('beforelevelid', $fhlevel['id'])->where('status', 2)->where('levelup_time', '>=', $og['createtime'])->group('mid')->order('levelup_time', 'asc')->column('mid');
						if($levelup_order_mids) {
							$levelup_order_member = Db::name('member')->whereIn('id',$levelup_order_mids)->column('id,total_fenhong_partner,levelstarttime','id');
							$midlist = array_merge((array)$midlist,(array) $levelup_order_member );
						}
					} catch (\Exception $e) {
						
					}
					if($sysset['partner_jiaquan'] == 1){
						$oldmidlist = $midlist;
						$midlist = array_merge((array)$lastmidlist,(array)$midlist);
						$lastmidlist = array_merge((array)$lastmidlist,(array)$oldmidlist);
					}
					if(!$midlist) continue;

					//股东贡献量分红 开启后可设置一定比例的分红金额按照股东的团队业绩量分红
					$pergxcommon = 0;
					if($sysset['partner_gongxian']==1 && $fhlevel['fenhong_gongxian_percent'] > 0){
						$gongxian_percent = $fhlevel['fenhong'] * $fhlevel['fenhong_gongxian_percent']*0.01;
						$fhlevel['fenhong'] = $fhlevel['fenhong'] * (1 - $fhlevel['fenhong_gongxian_percent']*0.01);
						$gongxianCommissionTotal = $gongxian_percent * $fenhongprice * 0.01;
						//总业绩
						//$levelids = Db::name('member_level')->where('aid',$aid)->where('sort','<',$fhlevel['sort'])->column('id');
						$levelids = Db::name('member_level')->where('aid',$aid)->column('id');
						$yejiwhere = [];
						$yejiwhere[] = ['createtime','>=',$starttime];
						$yejiwhere[] = ['createtime','<',$endtime];
						$yejiwhere[] = ['isfenhong','=',0];
						//if($sysset['fhjiesuantime_type'] == 1) {
							$yejiwhere[] = ['status','in','1,2,3'];
						//}else{
						//	$yejiwhere[] = ['status','=','3'];
						//}
						$totalyeji = 0;
						foreach($midlist as $kk=>$item){
							$downmids = \app\common\Member::getteammids($aid,$item['id'],999,$levelids);
							$yeji = Db::name('shop_order')->where('aid',$aid)->where('mid','in',$downmids)->where($yejiwhere)->sum('totalprice');
							$midlist[$kk]['yeji'] = $yeji;
							$totalyeji += $yeji;
						}
						if($totalyeji > 0){
							$pergxcommon = $gongxianCommissionTotal / $totalyeji;
						}else{
							$pergxcommon = 0;
						}
					}

					//$commission = $fhlevel['fenhong'] * $fenhongprice * 0.01 / count($midlist);//平均分给此等级的会员
					$totalcommission = 0;
					if($og['module'] == 'yuyue'){
						$product = Db::name('yuyue_product')->where('id',$og['proid'])->find();
					}else{
						$product = Db::name('shop_product')->where('id',$og['proid'])->find();
					}
					if($product['gdfenhongset']==1){//按比例
						$fenhongdata = json_decode($product['gdfenhongdata1'],true);
						if($fenhongdata){
							$totalcommission = $fenhongdata[$fhlevel['id']]['commission'] * $fenhongprice * 0.01;
						}
					}elseif($product['gdfenhongset']==2){//按固定金额
						$fenhongdata = json_decode($product['gdfenhongdata2'],true);
						if($fenhongdata){
							$totalcommission = $fenhongdata[$fhlevel['id']]['commission'] * $og['num'];
						}
					}elseif($product['gdfenhongset'] == 0){
						$totalcommission = $fhlevel['fenhong'] * $fenhongprice * 0.01;
					}
					if($totalcommission == 0) continue;

					$commission = $totalcommission / count($midlist);
					

					if(!$midfhArr['level_'.$fhlevel['id']]) $midfhArr['level_'.$fhlevel['id']] = [];
					$newcommission = 0;
					foreach($midlist as $item){
						$mid = $item['id'];
						if($isyj == 1 && $mid == $yjmid && $commission > 0){
							$commissionyj += $commission;
							$og['commission'] = round($commission,2);
							$og['fhname'] = t('股东分红',$aid);
							$newoglist[] = $og;
							break;
						}
						$gxcommon = 0;
						if($pergxcommon > 0){
							if($item['yeji'] >= $fhlevel['fenhong_gongxian_minyeji']){
								$gxcommon = $item['yeji'] * $pergxcommon;
							}
						}
						$newcommission = $commission + $gxcommon;
						if($midfhArr['level_'.$fhlevel['id']][$mid]){
							if($fhlevel['fenhong_max_money'] > 0) {
								if($midfhArr['level_'.$fhlevel['id']][$mid]['totalcommission'] + $newcommission + $item['total_fenhong_partner'] > $fhlevel['fenhong_max_money']) {
									//Log::write('大于最大分红金额'.$commission);
									$newcommission = $fhlevel['fenhong_max_money'] - $midfhArr['level_'.$fhlevel['id']][$mid]['totalcommission'] - $item['total_fenhong_partner'];
								}
							}
							if($commissionpercent != 1){
								$fenhongcommission = round($newcommission*$commissionpercent,2);
								$fenhongmoney = round($newcommission*$moneypercent,2);
							}else{
								$fenhongcommission = $newcommission;
								$fenhongmoney = 0;
							}
							$midfhArr['level_'.$fhlevel['id']][$mid]['totalcommission'] = $midfhArr['level_'.$fhlevel['id']][$mid]['totalcommission'] + $newcommission;
							$midfhArr['level_'.$fhlevel['id']][$mid]['commission'] = $midfhArr['level_'.$fhlevel['id']][$mid]['commission'] + $fenhongcommission;
							$midfhArr['level_'.$fhlevel['id']][$mid]['money'] = $midfhArr['level_'.$fhlevel['id']][$mid]['money'] + $fenhongmoney;
							$midfhArr['level_'.$fhlevel['id']][$mid]['ogids'][] = $og['id'];
						}else{
							if($fhlevel['fenhong_max_money'] > 0) {
								if($newcommission + $item['total_fenhong_partner'] > $fhlevel['fenhong_max_money']) {
									$newcommission = $fhlevel['fenhong_max_money'] - $item['total_fenhong_partner'];
								}
							}
							if($commissionpercent != 1){
								$fenhongcommission = round($newcommission*$commissionpercent,2);
								$fenhongmoney = round($newcommission*$moneypercent,2);
							}else{
								$fenhongcommission = $newcommission;
								$fenhongmoney = 0;
							}
							$midfhArr['level_'.$fhlevel['id']][$mid] = [
								'totalcommission'=>$newcommission,
								'commission'=>$fenhongcommission,
								'money'=>$fenhongmoney,
								'ogids'=>[$og['id']],
								'module'=>$og['module'] ?? 'shop',
							];
						}
					}
				}
			}
			if($isyj == 0 && $sysset['fhjiesuanhb'] == 0) {
				if($midfhArr){
					foreach($midfhArr as $levelstr=>$midfhArr2){
						$levelid = explode('_',$levelstr)[1];
						$levelname = $fhlevellist[$levelid]['name'];
						$remark = t('股东分红',$aid);
						self::fafang($aid,$midfhArr2,'fenhong',$remark);
					}
				}
				$midfhArr = [];
			}
		}
		if($isyj == 0 && $sysset['fhjiesuanhb'] == 1) {
			if($midfhArr){
				foreach($midfhArr as $levelstr=>$midfhArr2){
					$levelid = explode('_',$levelstr)[1];
					$levelname = $fhlevellist[$levelid]['name'];
					$remark = t('股东分红',$aid);
					self::fafang($aid,$midfhArr2,'fenhong',$remark);
				}
			}
		}
		if($isyj == 1){
			return ['commissionyj'=>round($commissionyj,2),'oglist'=>$newoglist];
		}
	}
	//团队分红
	public static function teamfenhong($aid,$sysset,$oglist,$starttime=0,$endtime=0,$isyj=0,$yjmid=0){
		if($endtime == 0) $endtime = time();
		if(getcustom('plug_ttdz')) return ['commissionyj'=>0,'oglist'=>[]];
		if($isyj == 1 && !$oglist){
			//多商户的商品是否参与分红
			if($sysset['fhjiesuanbusiness'] == 1){
				$bwhere = '1=1';
			}else{
				$bwhere = [['og.bid','=','0']];
			}
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',$aid)->where('og.isfenhong',0)->where('og.status','in',[1,2,3])->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->order('og.id desc')->select()->toArray();
			if(!$oglist) $oglist = [];
			}
		//参与团队分红的等级
		$teamfhlevellist = Db::name('member_level')->where('aid',$aid)->where('teamfenhonglv','>','0')->column('*','id');
		if(!$teamfhlevellist) return ['commissionyj'=>0,'oglist'=>[]];
		
		
		if(!$oglist) return ['commissionyj'=>0,'oglist'=>[]];
		
		$defaultCid = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 1)->value('id');
		if($defaultCid) {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->where('cid', $defaultCid)->column('id');
		} else {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->column('id');
		}
		
		$isjicha = ($sysset['teamfenhong_differential'] == 1 ? true : false);
		$allfenhongprice = 0;
		$ogids = [];
		$midteamfhArr = [];
		$teamfenhong_orderids = [];
		$teamfenhong_orderids_cat = [];
		$newoglist = [];
		$commissionyj = 0;
		foreach($oglist as $og){
			$commissionyj_my = 0;
			if(false){}else{
				$commissionpercent = 1;
				$moneypercent = 0;
			}
			if($sysset['fhjiesuantype'] == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'] * $og['num'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$allfenhongprice = $allfenhongprice + $fenhongprice;
			$member = Db::name('member')->where('id', $og['mid'])->find();
			$member_extend = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('mid', $og['mid'])->find();
			
			if($teamfhlevellist){
				$pids = Db::name('member')->where('id',$og['mid'])->value('path');
				if($pids){
					$pids .= ','.$og['mid'];
				}else{
					$pids = (string)$og['mid'];
				}
				if($pids){
					$parentList = Db::name('member')->where('id','in',$pids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
					$parentList = array_reverse($parentList);
					$hasfhlevelids = [];
					$last_teamfenhongbl = 0;
					$last_teamfenhongmoney = 0;
					$last_level_teamfenhongbl = 0;
					$has_level_fhlevelids = [];
					foreach($parentList as $k=>$parent){
						//判断升级时间
						$leveldata = $teamfhlevellist[$parent['levelid']];
						if($parent['levelstarttime'] >= $og['createtime']) {
							$levelup_order_levelid = Db::name('member_levelup_order')->where('aid',$aid)->where('mid', $parent['id'])->where('status', 2)
								->where('levelup_time', '<=', $og['createtime'])->whereIn('levelid',$defaultLevelIds)->order('levelup_time', 'desc')->value('beforelevelid');
							if($levelup_order_levelid) {
								$parent['levelid'] = $levelup_order_levelid;
								$leveldata = $teamfhlevellist[$parent['levelid']];
							}
						}

						if(!$leveldata || $k>=$leveldata['teamfenhonglv']) continue;
						if($parent['id'] == $og['mid'] && $leveldata['teamfenhong_self'] != 1) continue;
						if($leveldata['teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
						$hasfhlevelids[] = $parent['levelid'];
						
						if($og['module'] != 'luckycollage'){
							if($og['module'] == 'yuyue'){
								$product = Db::name('yuyue_product')->where('id',$og['proid'])->find();
							}else{
								$product = Db::name('shop_product')->where('id',$og['proid'])->find();
							}
							if($product['teamfenhongset'] == 1){ //按比例
								$fenhongdata = json_decode($product['teamfenhongdata1'],true);
								if($fenhongdata){
									$leveldata['teamfenhongbl'] = $fenhongdata[$leveldata['id']]['commission'];
									$leveldata['teamfenhong_money'] = 0;
								}
							}elseif($product['teamfenhongset'] == 2){ //按固定金额
								$fenhongdata = json_decode($product['teamfenhongdata2'],true);
								if($fenhongdata){
									$leveldata['teamfenhongbl'] = 0;
									$leveldata['teamfenhong_money'] = $fenhongdata[$leveldata['id']]['commission'] * $og['num'];
								}
							}elseif($product['teamfenhongset'] == -1){
								$leveldata['teamfenhongbl'] = 0;
								$leveldata['teamfenhong_money'] = 0;
							}

							if($product['teamfenhongpjset'] == 1){ //按比例
								$fenhongpjdata = json_decode($product['teamfenhongpjdata1'],true);
								if($fenhongpjdata){
									$leveldata['teamfenhong_pingji_bl'] = $fenhongpjdata[$leveldata['id']]['commission'];
									$leveldata['teamfenhong_pingji_money'] = 0;
								}
							}elseif($product['teamfenhongpjset'] == 2){ //按固定金额
								$fenhongpjdata = json_decode($product['teamfenhongpjdata2'],true);
								if($fenhongpjdata){
									$leveldata['teamfenhong_pingji_bl'] = 0;
									$leveldata['teamfenhong_pingji_money'] = $fenhongpjdata[$leveldata['id']]['commission'] * $og['num'];
								}
							}elseif($product['teamfenhongpjset'] == -1){
								$leveldata['teamfenhong_pingji_bl'] = 0;
								$leveldata['teamfenhong_pingji_money'] = 0;
							}
						}

						//每单奖励
						$totalfenhongmoney = 0;
						if($leveldata['teamfenhong_money'] > 0 && !in_array($og['orderid'],$teamfenhong_orderids[$parent['id']])) {
							if($isjicha){
								$totalfenhongmoney = $totalfenhongmoney + $leveldata['teamfenhong_money'] - $last_teamfenhongmoney;
							}else{
								$totalfenhongmoney = $totalfenhongmoney + $leveldata['teamfenhong_money'];
							}
							if($totalfenhongmoney < 0) $totalfenhongmoney = 0;
							$last_teamfenhongmoney = $last_teamfenhongmoney + $totalfenhongmoney;
							$teamfenhong_orderids[$parent['id']][] = $og['orderid'];
						}
						//分红比例
						if($leveldata['teamfenhongbl'] > 0) {
							if($isjicha){
								$this_teamfenhongbl = $leveldata['teamfenhongbl'] - $last_teamfenhongbl;

								}else{
								$this_teamfenhongbl = $leveldata['teamfenhongbl'];
							}
							if($this_teamfenhongbl <=0) continue;
							$last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

							$totalfenhongmoney = $totalfenhongmoney + $this_teamfenhongbl * $fenhongprice * 0.01;
						}

						if($totalfenhongmoney > 0){
							if($isyj == 1 && $yjmid == $parent['id']){
								$commissionyj_my += $totalfenhongmoney;
							}
							if($commissionpercent != 1){
								$fenhongcommission = round($totalfenhongmoney*$commissionpercent,2);
								$fenhongmoney = round($totalfenhongmoney*$moneypercent,2);
							}else{
								$fenhongcommission = $totalfenhongmoney;
								$fenhongmoney = 0;
							}

							if($midteamfhArr[$parent['id']]){
								$midteamfhArr[$parent['id']]['totalcommission'] = $midteamfhArr[$parent['id']]['totalcommission'] + $totalfenhongmoney;
								$midteamfhArr[$parent['id']]['commission'] = $midteamfhArr[$parent['id']]['commission'] + $fenhongcommission;
								$midteamfhArr[$parent['id']]['money'] = $midteamfhArr[$parent['id']]['money'] + $fenhongmoney;
								$midteamfhArr[$parent['id']]['ogids'][] = $og['id'];
							}else{
								$midteamfhArr[$parent['id']] = [
									'totalcommission'=>$totalfenhongmoney,
									'commission'=>$fenhongcommission,
									'money'=>$fenhongmoney,
									'ogids'=>[$og['id']],
									'module'=>$og['module'] ?? 'shop'
								];
							}

							//平级奖 找最近的上级
							}
					}
					//其他分组等级
					}
			}
			if($isyj == 1 && $commissionyj_my > 0){
				$commissionyj += $commissionyj_my;
				$og['commission'] = round($commissionyj_my,2);
				$og['fhname'] = t('团队分红',$aid);
				$newoglist[] = $og;
			}

            if($isyj == 0 && $sysset['fhjiesuanhb'] == 0) {
				self::fafang($aid,$midteamfhArr,'teamfenhong',t('团队分红',$aid));
				$midteamfhArr = [];
			}
		}
		
		if($isyj == 1){
			return ['commissionyj'=>round($commissionyj,2),'oglist'=>$newoglist];
		}
		if($isyj == 0 && $sysset['fhjiesuanhb'] == 1) {
			self::fafang($aid,$midteamfhArr,'teamfenhong',t('团队分红',$aid));
		}
	}
	//区域代理分红
	public static function areafenhong($aid,$sysset,$oglist,$starttime=0,$endtime=0,$isyj=0,$yjmid=0){
		if($endtime == 0) $endtime = time();
		if($isyj == 1 && !$oglist){
			//多商户的商品是否参与分红
			if($sysset['fhjiesuanbusiness'] == 1){
				$bwhere = '1=1';
			}else{
				$bwhere = [['og.bid','=','0']];
			}
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',$aid)->where('og.isfenhong',0)->where('og.status','in',[1,2,3])->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->order('og.id desc')->select()->toArray();
			}
		if(!$oglist) return ['commissionyj'=>0,'oglist'=>[]];
		//参与区域代理分红的等级
		$areafhlevellist = Db::name('member_level')->where('aid',$aid)->where('areafenhong','>','0')->order('sort,id')->column('*','id');
		if(!$areafhlevellist) return ['commissionyj'=>0,'oglist'=>[]];
		if($sysset['areafenhong_jiaquan'] == 1){
			$largearealevelids = Db::name('member_level')->where('aid',$aid)->where('areafenhong','10')->where('areafenhongbl','>',0)->column('id');
			$provincelevelids = Db::name('member_level')->where('aid',$aid)->where('areafenhong','1')->where('areafenhongbl','>',0)->column('id');
			$citylevelids = Db::name('member_level')->where('aid',$aid)->where('areafenhong','2')->where('areafenhongbl','>',0)->column('id');
		}

		$defaultCid = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 1)->value('id');
		if($defaultCid) {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->where('cid', $defaultCid)->column('id');
		} else {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->column('id');
		}
		$memberlist1 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhong_city,areafenhong_area,areafenhongbl,areafenhong')->where('aid',$aid)->where('areafenhong',1)->where('areafenhongbl','>',0)->select()->toArray();
		$memberlist2 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhong_city,areafenhong_area,areafenhongbl,areafenhong')->where('aid',$aid)->where('areafenhong',2)->where('areafenhongbl','>',0)->select()->toArray();
		$memberlist3 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhong_city,areafenhong_area,areafenhongbl,areafenhong')->where('aid',$aid)->where('areafenhong',3)->where('areafenhongbl','>',0)->select()->toArray();
		$memberlist10 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhong_city,areafenhong_area,areafenhong_largearea,areafenhongbl,areafenhong')->where('aid',$aid)->where('areafenhong',10)->where('areafenhongbl','>',0)->select()->toArray();

		$areamemberlist = array_merge((array)$memberlist1,(array)$memberlist2,(array)$memberlist3,(array)$memberlist10);
		//其他分组等级
		$member_level_record = Db::name('member_level_record')->field('mid id,levelid,areafenhong_province,areafenhong_city,areafenhong_area,areafenhongbl,areafenhong')->where('aid',$aid)->whereIn('areafenhong',[1,2,3])->where('areafenhongbl','>',0)->select()->toArray();
		$areamemberlist = array_merge((array)$areamemberlist, (array)$member_level_record);

		$isjicha = ($sysset['areafenhong_differential'] == 1 ? true : false);
		$ogids = [];
		$midareafhArr = [];

		$newoglist = [];
		$commissionyj = 0;
		foreach($oglist as $og){
			$commissionyj_my = 0;
			if(false){}else{
				$commissionpercent = 1;
				$moneypercent = 0;
			}
			if($sysset['fhjiesuantype'] == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'] * $og['num'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$allfenhongprice = $allfenhongprice + $fenhongprice;
			$member = Db::name('member')->where('id', $og['mid'])->find();
			$member_extend = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('mid', $og['mid'])->find();
			
			if($og['module'] == 'yuyue'){
				$product = Db::name('yuyue_product')->where('id',$og['proid'])->find();
			}else{
				$product = Db::name('shop_product')->where('id',$og['proid'])->find();
			}
			$last_areafenhongbl = 0;
			$last_areafenhongmoney = 0;

			if(!getcustom('plug_ttdz') || $og['isfg']==1){
				//区域代理分红
				$areaArr = explode(',',$og['area2']);
				$province = $areaArr[0];
				$city = $areaArr[1];
				$area = $areaArr[2];
				foreach($areafhlevellist as $fhlevel){
					
					if($product['areafenhongset'] == 1){ //按比例
						$fenhongdata = json_decode($product['areafenhongdata1'],true);
						if($fenhongdata){
							$fhlevel['areafenhongbl'] = $fenhongdata[$fhlevel['id']]['commission'];
							$fhlevel['areafenhong_money'] = 0;
						}
					}elseif($product['areafenhongset'] == 2){ //按固定金额
						$fenhongdata = json_decode($product['areafenhongdata2'],true);
						if($fenhongdata){
							$fhlevel['areafenhongbl'] = 0;
							$fhlevel['areafenhong_money'] = $fenhongdata[$fhlevel['id']]['commission'] * $og['num'];
						}
					}elseif($product['areafenhongset'] == -1){
						$fhlevel['areafenhongbl'] = 0;
						$fhlevel['areafenhong_money'] = 0;
					}else{
						$fhlevel['areafenhong_money'] = 0;
					}

					if($fhlevel['areafenhongbl']==0 && $fhlevel['areafenhong_money']==0) continue;

					if($fhlevel['areafenhong'] == 3 && $province && $city && $area){
						$memberlist = Db::name('member')->field('id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid',$fhlevel['id'])->where('areafenhong',0)->where('areafenhong_province',$province)->where('areafenhong_city',$city)->where('areafenhong_area',$area)->select()->toArray();
						if($sysset['areafenhong_jiaquan'] == 1 && $largearealevelids){ //大区代理也参与
							$largeareaList = Db::name('largearea')->where("find_in_set('{$province}',province)")->where('status',1)->column('name');
							$memberlist10 = Db::name('member')->field('id,levelid,areafenhong_largearea,areafenhongbl,areafenhong')->where('levelid','in',$largearealevelids)->where('areafenhong',0)->where('areafenhong_largearea','in',$largeareaList)->select()->toArray();
							$memberlist = array_merge((array)$memberlist, (array)$memberlist10);
						}
						if($sysset['areafenhong_jiaquan'] == 1 && ($provincelevelids || $citylevelids)){ 
							if($provincelevelids){
								$memberlist1 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid','in',$provincelevelids)->where('areafenhong',0)->where('areafenhong_province',$province)->select()->toArray();
							}else{
								$memberlist1 = [];
							}
							if($citylevelids){
								$memberlist2 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid','in',$citylevelids)->where('areafenhong',0)->where('areafenhong_province',$province)->where('areafenhong_city',$city)->select()->toArray();
							}else{
								$memberlist2 = [];
							}
							$memberlist = array_merge((array)$memberlist, (array)$memberlist1, (array)$memberlist2);
							//Log::write('$memberlist 3');
							//Log::write($memberlist);
						}
					}
					if($fhlevel['areafenhong'] == 2 && $province && $city){
						$memberlist = Db::name('member')->field('id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid',$fhlevel['id'])->where('areafenhong',0)->where('areafenhong_province',$province)->where('areafenhong_city',$city)->select()->toArray();
						if($sysset['areafenhong_jiaquan'] == 1 && $largearealevelids){ //大区代理也参与
							$largeareaList = Db::name('largearea')->where("find_in_set('{$province}',province)")->where('status',1)->column('name');
							$memberlist10 = Db::name('member')->field('id,levelid,areafenhong_largearea,areafenhongbl,areafenhong')->where('levelid','in',$largearealevelids)->where('areafenhong',0)->where('areafenhong_largearea','in',$largeareaList)->select()->toArray();
							$memberlist = array_merge((array)$memberlist, (array)$memberlist10);
						}
						if($sysset['areafenhong_jiaquan'] == 1 && $provincelevelids){ //省级代理也参与
							$memberlist1 = Db::name('member')->field('id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid','in',$provincelevelids)->where('areafenhong',0)->where('areafenhong_province',$province)->select()->toArray();
							$memberlist = array_merge((array)$memberlist, (array)$memberlist1);
							//Log::write('$memberlist 2');
							//Log::write($memberlist);
						}
					}
					if($fhlevel['areafenhong'] == 1 && $province){
						$memberlist = Db::name('member')->field('id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid',$fhlevel['id'])->where('areafenhong',0)->where('areafenhong_province',$province)->select()->toArray();
						if(getcustom('plug_sanyang'))
						$memberlist_extend = Db::name('member_level_record')->field('mid id,levelid,areafenhong_province,areafenhongbl,areafenhong')->where('levelid',$fhlevel['id'])->where('areafenhong',0)->where('areafenhong_province',$province)->select()->toArray();
						
						if($sysset['areafenhong_jiaquan'] == 1 && $largearealevelids){ //大区代理也参与
							$largeareaList = Db::name('largearea')->where("find_in_set('{$province}',province)")->where('status',1)->column('name');
							$memberlist10 = Db::name('member')->field('id,levelid,areafenhong_largearea,areafenhongbl,areafenhong')->where('levelid','in',$largearealevelids)->where('areafenhong',0)->where('areafenhong_largearea','in',$largeareaList)->select()->toArray();
							$memberlist = array_merge((array)$memberlist, (array)$memberlist10);
						}
					}
					if($fhlevel['areafenhong'] == 10 && $province){
						$largeareaList = Db::name('largearea')->where("find_in_set('{$province}',province)")->where('status',1)->column('name');
						$memberlist = Db::name('member')->field('id,levelid,areafenhong_largearea,areafenhongbl,areafenhong')->where('levelid',$fhlevel['id'])->where('areafenhong',0)->where('areafenhong_largearea','in',$largeareaList)->select()->toArray();
					}
					if($memberlist){
						
						$this_areafenhongbl = $fhlevel['areafenhongbl'];
						if($this_areafenhongbl > 0 && $isjicha){
							$this_areafenhongbl = $fhlevel['areafenhongbl'] - $last_areafenhongbl;
						}
						$last_areafenhongbl = $last_areafenhongbl + $this_areafenhongbl;
						
						$areafenhong_money = $fhlevel['areafenhong_money'];
						if($fhlevel['areafenhong_money'] > 0 && $isjicha){
							$areafenhong_money = $fhlevel['areafenhong_money'] - $last_areafenhongmoney;
						}
						$last_areafenhongmoney = $last_areafenhongmoney + $areafenhong_money;

						$commission = ($this_areafenhongbl * $fenhongprice * 0.01 + $areafenhong_money) / count($memberlist);
						if($commission <= 0) continue;
						//Log::write('$commission');
						//Log::write($commission);
						if($commissionpercent != 1){
							$fenhongcommission = round($commission*$commissionpercent,2);
							$fenhongmoney = round($commission*$moneypercent,2);
						}else{
							$fenhongcommission = $commission;
							$fenhongmoney = 0;
						}

						foreach($memberlist as $member){
							$mid = $member['id'];
							if($isyj == 1 && $yjmid == $mid){
								$commissionyj_my += $commission;
							}
							if($midareafhArr[$mid]){
								$midareafhArr[$mid]['totalcommission'] = $midareafhArr[$mid]['totalcommission'] + $commission;
								$midareafhArr[$mid]['commission'] = $midareafhArr[$mid]['commission'] + $fenhongcommission;
								$midareafhArr[$mid]['money'] = $midareafhArr[$mid]['money'] + $fenhongmoney;
								$midareafhArr[$mid]['ogids'][] = $og['id'];
							}else{
								$midareafhArr[$mid] = [
									'totalcommission'=>$commission,
									'commission'=>$fenhongcommission,
									'money'=>$fenhongmoney,
									'ogids'=>[$og['id']],
									'module'=>$og['module'] ?? 'shop'
								];
							}
						}
					}
				}
				//单独设置的区域代理
				if($areamemberlist){
					foreach($areamemberlist as $member){
						if(
							($member['areafenhong']==1 && $member['areafenhong_province'] == $province) || 
							($member['areafenhong']==2 && $member['areafenhong_province'] == $province && $member['areafenhong_city'] == $city) || 
							($member['areafenhong']==3 && $member['areafenhong_province'] == $province && $member['areafenhong_city'] == $city && $member['areafenhong_area'] == $area) || 
							($member['areafenhong']==10 && in_array($member['areafenhong_largearea'],Db::name('largearea')->where("find_in_set('{$province}',province)")->where('status',1)->column('name')))
						){
							$commission = $fenhongprice * 0.01 * $member['areafenhongbl'];
							
							$mid = $member['id'];
							if($isyj == 1 && $yjmid == $mid){
								$commissionyj_my += $commission;
							}
							if($commissionpercent != 1){
								$fenhongcommission = round($commission*$commissionpercent,2);
								$fenhongmoney = round($commission*$moneypercent,2);
							}else{
								$fenhongcommission = $commission;
								$fenhongmoney = 0;
							}
							if($midareafhArr[$mid]){
								$midareafhArr[$mid]['totalcommission'] = $midareafhArr[$mid]['totalcommission'] + $commission;
								$midareafhArr[$mid]['commission'] = $midareafhArr[$mid]['commission'] + $fenhongcommission;
								$midareafhArr[$mid]['money'] = $midareafhArr[$mid]['money'] + $fenhongmoney;
								$midareafhArr[$mid]['ogids'][] = $og['id'];
							}else{
								$midareafhArr[$mid] = [
									'totalcommission'=>$commission,
									'commission'=>$fenhongcommission,
									'money'=>$fenhongmoney,
									'ogids'=>[$og['id']],
									'module'=>$og['module'] ?? 'shop'
								];
							}
						}
					}
				}
			}
			if($isyj == 1 && $commissionyj_my > 0){
				$commissionyj += $commissionyj_my;
				$og['commission'] = round($commissionyj_my,2);
				$og['fhname'] = t('区域代理分红',$aid);
				$newoglist[] = $og;
			}
			if($isyj == 0 && $sysset['fhjiesuanhb'] == 0) {
				self::fafang($aid,$midareafhArr,'areafenhong',t('区域代理分红',$aid));
				$midareafhArr = [];
			}
		}
		if($isyj == 1){
			return ['commissionyj'=>round($commissionyj,2),'oglist'=>$newoglist];
		}
		if($isyj == 0 && $sysset['fhjiesuanhb'] == 1) {
			self::fafang($aid,$midareafhArr,'areafenhong',t('区域代理分红',$aid));
		}
	}
	//商品团队分红
	public static function product_teamfenhong($aid,$sysset,$oglist,$starttime=0,$endtime=0,$isyj=0,$yjmid=0){
		if($endtime == 0) $endtime = time();
		if(!getcustom('product_teamfenhong')) return ['commissionyj'=>0,'oglist'=>[]];
		if($isyj == 1 && !$oglist){
			//多商户的商品是否参与分红
			if($sysset['fhjiesuanbusiness'] == 1){
				$bwhere = '1=1';
			}else{
				$bwhere = [['og.bid','=','0']];
			}
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',$aid)->where('og.isfenhong',0)->where('og.status','in',[1,2,3])->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->order('og.id desc')->select()->toArray();
		}
		if(!$oglist) return ['commissionyj'=>0,'oglist'=>[]];
		//参与商品团队分红的等级
        $product_fhlevellist = Db::name('member_level')->where('aid',$aid)->where('product_teamfenhonglv','>','0')->where('product_teamfenhong_money','>',0)->where('product_teamfenhong_ids','<>','')->column('id,cid,name,product_teamfenhonglv,product_teamfenhong_ids,product_teamfenhongonly,product_teamfenhong_money,product_teamfenhong_self','id');
		if(!$product_fhlevellist) return ['commissionyj'=>0,'oglist'=>[]];
		
		$defaultCid = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 1)->value('id');
		if($defaultCid) {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->where('cid', $defaultCid)->column('id');
		} else {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->column('id');
		}

		$isjicha = ($sysset['teamfenhong_differential'] == 1 ? true : false);
		$ogids = [];
		$mid_product_teamfhArr = [];
		
		$newoglist = [];
		$commissionyj = 0;
		foreach($oglist as $og){
			$commissionyj_my = 0;
			if(false){}else{
				$commissionpercent = 1;
				$moneypercent = 0;
			}
			if($sysset['fhjiesuantype'] == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'] * $og['num'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$allfenhongprice = $allfenhongprice + $fenhongprice;
			$member = Db::name('member')->where('id', $og['mid'])->find();
			$member_extend = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('mid', $og['mid'])->find();
			
			$prolevelids = [];
			foreach ($product_fhlevellist as $item_pl) {
				if(in_array($og['proid'],explode(',',$item_pl['product_teamfenhong_ids']))) {
					$prolevelids[] = $item_pl['id'];
				}
			}
			$pids = Db::name('member')->where('id',$og['mid'])->value('path');
			if($pids){
				$pids .= ','.$og['mid']; 
			}else{
				$pids = (string)$og['mid'];
			}
			if($pids){
				$parentList = Db::name('member')->where('id','in',$pids)->where('levelid','in',$prolevelids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
				$parentList = array_reverse($parentList);
				$hasfhlevelids = [];
				$last_teamfenhongbl = 0;
				foreach($parentList as $k=>$parent){
					$leveldata = $product_fhlevellist[$parent['levelid']];
					if($parent['levelstarttime'] >= $og['createtime']) {
						$levelup_order_levelid = Db::name('member_levelup_order')->where('aid',$aid)->where('mid', $parent['id'])->where('status', 2)
							->where('levelup_time', '>=', $og['createtime'])->whereIn('levelid',$defaultLevelIds)->order('levelup_time', 'asc')->value('beforelevelid');
						if($levelup_order_levelid) {
							$parent['levelid'] = $levelup_order_levelid;
							$leveldata = $product_fhlevellist[$parent['levelid']];
						}
					}
					if(!$leveldata || $k>=$leveldata['product_teamfenhonglv']) continue;
					if($parent['id'] == $og['mid'] && $leveldata['product_teamfenhong_self'] != 1) continue;
					//每单奖励
					if($leveldata['product_teamfenhong_money'] > 0) {
						if($leveldata['product_teamfenhonglv'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
						$hasfhlevelids[] = $parent['levelid'];
						$commission = $leveldata['product_teamfenhong_money'] * $og['num'];
						if($isyj == 1 && $yjmid == $parent['id']){
							$commissionyj_my += $commission;
						}

						if($commissionpercent != 1){
							$fenhongcommission = round($commission*$commissionpercent,2);
							$fenhongmoney = round($commission*$moneypercent,2);
						}else{
							$fenhongcommission = $commission;
							$fenhongmoney = 0;
						}

						if($mid_product_teamfhArr[$parent['id']]){
							$mid_product_teamfhArr[$parent['id']]['totalcommission'] = $mid_product_teamfhArr[$parent['id']]['totalcommission'] + $commission;
							$mid_product_teamfhArr[$parent['id']]['commission'] = $mid_product_teamfhArr[$parent['id']]['commission'] + $fenhongcommission;
							$mid_product_teamfhArr[$parent['id']]['money'] = $mid_product_teamfhArr[$parent['id']]['money'] + $fenhongmoney;
							$mid_product_teamfhArr[$parent['id']]['ogids'][] = $og['id'];
						}else{
							$mid_product_teamfhArr[$parent['id']] = ['totalcommission'=>$commission,'commission'=>$fenhongcommission,'money'=>$fenhongmoney,'ogids'=>[$og['id']]];
						}
					}
				}
				//其他分组等级
				}
			if($isyj == 1 && $commissionyj_my > 0){
				$commissionyj += $commissionyj_my;
				$og['commission'] = round($commissionyj_my,2);
				$og['fhname'] = t('商品团队分红',$aid);
				$newoglist[] = $og;
			}
            if($isyj == 0 && $sysset['fhjiesuanhb'] == 0) {
				self::fafang($aid,$mid_product_teamfhArr,'product_teamfenhong',t('商品团队分红',$aid));
				$mid_product_teamfhArr = [];
			}
		}
		if($isyj == 1){
			return ['commissionyj'=>round($commissionyj,2),'oglist'=>$newoglist];
		}
		if($isyj == 0 && $sysset['fhjiesuanhb'] == 1) {
			self::fafang($aid,$mid_product_teamfhArr,'product_teamfenhong',t('商品团队分红',$aid));
		}
	}
	//等级团队分红
	public static function level_teamfenhong($aid,$sysset,$oglist,$starttime=0,$endtime=0,$isyj=0,$yjmid=0){
		if($endtime == 0) $endtime = time();
		if(!getcustom('level_teamfenhong')) return ['commissionyj'=>0,'oglist'=>[]];
		if($isyj == 1 && !$oglist){
			//多商户的商品是否参与分红
			if($sysset['fhjiesuanbusiness'] == 1){
				$bwhere = '1=1';
			}else{
				$bwhere = [['og.bid','=','0']];
			}
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',$aid)->where('og.isfenhong',0)->where('og.status','in',[1,2,3])->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->order('og.id desc')->select()->toArray();
		}
		if(!$oglist) return ['commissionyj'=>0,'oglist'=>[]];
		//参与等级团队分红的等级
        $level_teamfhlevellist = Db::name('member_level')->where('aid',$aid)->where('level_teamfenhong_ids','<>','')->where('level_teamfenhonglv','>','0')->where(function ($query) {
			$query->where('level_teamfenhongbl','>',0)->whereOr('level_teamfenhong_money','>',0);
		})->column('id,cid,name,level_teamfenhong_ids,level_teamfenhonglv,level_teamfenhongbl,level_teamfenhongonly,level_teamfenhong_money','id');
		if(!$level_teamfhlevellist) return ['commissionyj'=>0,'oglist'=>[]];

		$defaultCid = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 1)->value('id');
		if($defaultCid) {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->where('cid', $defaultCid)->column('id');
		} else {
			$defaultLevelIds = Db::name('member_level')->where('aid',$aid)->column('id');
		}
		$isjicha = ($sysset['teamfenhong_differential'] == 1 ? true : false);
		$ogids = [];
		$midlevel_teamfhArr = [];
		$level_teamfenhong_orderids = [];
		$level_teamfenhong_orderids_cat = [];

		$newoglist = [];
		$commissionyj = 0;
		foreach($oglist as $og){
			if(false){}else{
				$commissionpercent = 1;
				$moneypercent = 0;
			}
			if($sysset['fhjiesuantype'] == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'] * $og['num'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$allfenhongprice = $allfenhongprice + $fenhongprice;
			$member = Db::name('member')->where('id', $og['mid'])->find();
			$member_extend = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('mid', $og['mid'])->find();
			
			$pids = Db::name('member')->where('id',$og['mid'])->value('path');
			if($pids){
				//查询符合等级条件的
				$level_teamfenhong_ids = [];
				$level_teamfenhong_parent_ids = [];
				foreach($level_teamfhlevellist as $level) {
					$level_teamfenhong_parent_ids = [$level['id']];
					$parentList = Db::name('member')->where('id','in',$pids)->whereIn('levelid',$level_teamfenhong_parent_ids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
					$parentList = array_reverse($parentList);
					$hasfhlevelids = [];
					$last_teamfenhongbl = 0;
					//if(count($parentList) <= 1) continue;
					foreach($parentList as $k=>$parent){
						//if($k > 1) continue;
						$leveldata = $level_teamfhlevellist[$parent['levelid']];
						if($parent['levelstarttime'] >= $og['createtime']) {
							$levelup_order_levelid = Db::name('member_levelup_order')->where('aid',$aid)->where('mid', $parent['id'])->where('status', 2)
								->where('levelup_time', '>=', $og['createtime'])->whereIn('levelid',$defaultLevelIds)->order('levelup_time', 'asc')->value('beforelevelid');
							if($levelup_order_levelid) {
								$parent['levelid'] = $levelup_order_levelid;
								$leveldata = $level_teamfhlevellist[$parent['levelid']];
							}
						}
						if(!$leveldata /*|| $k>=$leveldata['level_teamfenhonglv']*/) continue;
						//最近的上级分不分看当前会员是达到级别
						if($k == 0) {
							if(!in_array($member['levelid'], explode(',',(string)$leveldata['level_teamfenhong_ids']))) continue;
						}
						//每单奖励
						if($leveldata['level_teamfenhong_money'] > 0 && !in_array($og['orderid'], $level_teamfenhong_orderids[$parent['id']])) {
							if($leveldata['level_teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
							$hasfhlevelids[] = $parent['levelid'];
							$commission = $leveldata['level_teamfenhong_money'];
							if($isyj == 1 && $yjmid == $parent['id']){
								$commissionyj_my += $commission;
							}

							if($commissionpercent != 1){
								$fenhongcommission = round($commission*$commissionpercent,2);
								$fenhongmoney = round($commission*$moneypercent,2);
							}else{
								$fenhongcommission = $commission;
								$fenhongmoney = 0;
							}

							if($midlevel_teamfhArr[$parent['id']]){
								$midlevel_teamfhArr[$parent['id']]['totalcommission'] = $midlevel_teamfhArr[$parent['id']]['totalcommission'] + $commission;
								$midlevel_teamfhArr[$parent['id']]['commission'] = $midlevel_teamfhArr[$parent['id']]['commission'] + $fenhongcommission;
								$midlevel_teamfhArr[$parent['id']]['money'] = $midlevel_teamfhArr[$parent['id']]['money'] + $fenhongmoney;
								$midlevel_teamfhArr[$parent['id']]['ogids'][] = $og['id'];
							}else{
								$midlevel_teamfhArr[$parent['id']] = ['totalcommission'=>$commission,'commission'=>$fenhongcommission,'money'=>$fenhongmoney,'ogids'=>[$og['id']]];
							}
							$level_teamfenhong_orderids[$parent['id']][] = $og['orderid'];
						}
						//分红比例
						if($leveldata['level_teamfenhongbl'] > 0) {
							if($isjicha){
								$this_teamfenhongbl = $leveldata['level_teamfenhongbl'] - $last_teamfenhongbl;
							}else{
								$this_teamfenhongbl = $leveldata['level_teamfenhongbl'];
							}
							if($this_teamfenhongbl <=0) continue;
							$last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

							if($leveldata['level_teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
							$hasfhlevelids[] = $parent['levelid'];

							$commission = $this_teamfenhongbl * $fenhongprice * 0.01;
							if($isyj == 1 && $yjmid == $parent['id']){
								$commissionyj_my += $commission;
							}

							if($commissionpercent != 1){
								$fenhongcommission = round($commission*$commissionpercent,2);
								$fenhongmoney = round($commission*$moneypercent,2);
							}else{
								$fenhongcommission = $commission;
								$fenhongmoney = 0;
							}

							if($midlevel_teamfhArr[$parent['id']]){
								$midlevel_teamfhArr[$parent['id']]['totalcommission'] = $midlevel_teamfhArr[$parent['id']]['totalcommission'] + $commission;
								$midlevel_teamfhArr[$parent['id']]['commission'] = $midlevel_teamfhArr[$parent['id']]['commission'] + $fenhongcommission;
								$midlevel_teamfhArr[$parent['id']]['money'] = $midlevel_teamfhArr[$parent['id']]['money'] + $fenhongmoney;
								$midlevel_teamfhArr[$parent['id']]['ogids'][] = $og['id'];
							}else{
								$midlevel_teamfhArr[$parent['id']] = ['totalcommission'=>$commission,'commission'=>$fenhongcommission,'money'=>$fenhongmoney,'ogids'=>[$og['id']]];
							}
						}
					}
					//其他分组等级
					}
			}
			if($isyj == 1 && $commissionyj_my > 0){
				$commissionyj += $commissionyj_my;
				$og['commission'] = round($commissionyj_my,2);
				$og['fhname'] = t('等级团队分红',$aid);
				$newoglist[] = $og;
			}
			if($isyj == 0 && $sysset['fhjiesuanhb'] == 0) {
				self::fafang($aid,$midlevel_teamfhArr,'level_teamfenhong',t('等级团队分红',$aid));
				$midlevel_teamfhArr = [];
			}
		}
		if($isyj == 1){
			return ['commissionyj'=>round($commissionyj,2),'oglist'=>$newoglist];
		}
		if($isyj == 0 && $sysset['fhjiesuanhb'] == 1) {
			self::fafang($aid,$midlevel_teamfhArr,'level_teamfenhong',t('等级团队分红',$aid));
		}
	}
	public static function fafang($aid,$fhArr,$type,$remark){
		if(!$fhArr) return [];
		foreach($fhArr as $mid=>$midfh){
			$totalcommission = round($midfh['totalcommission'],2);
			$commission = round($midfh['commission'],2);
			$money = round($midfh['money'],2);
			//	var_dump($midfh);
			//	var_dump($midfh['totalcommission']);
			if($totalcommission > 0) {
				$fhdata = [];
				$fhdata['aid'] = $aid;
				$fhdata['mid'] = $mid;
				$fhdata['commission'] = $totalcommission;
				$fhdata['remark'] = $remark;
				$fhdata['type'] = $type;
				$fhdata['createtime'] = time();
				$fhdata['ogids'] = implode(',',$midfh['ogids']);
				$fhdata['module'] = $midfh['module'];
//				var_dump($fhdata);
				Db::name('member_fenhonglog')->insert($fhdata);
			}
			if($commission > 0){
				\app\common\Member::addcommission($aid,$mid,0,$commission,$fhdata['remark'],1,$type);
                //分红到账通知
                }
			if($money > 0){
				\app\common\Member::addmoney($aid,$mid,$money,$fhdata['remark']);
			}
		}
	}
}